<template>
  <BasicModal
    width="800px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    okText="保存"
    :maskClosable="false"
  >
    <Table
      :row-selection="{ selectedRowKeys: permissionSelectedRowKeys, onChange: onSelectChange }"
      :columns="permissionColumns"
      :data-source="permissionList"
      :pagination="false"
      :row-key="'id'"
      bordered
    >
      <template #bodyCell="{ column, text, index }">
        <template v-if="column.dataIndex === 'serialNumber'">
          <div>
            <span> {{ index + 1 }}</span>
          </div>
        </template>
        <template
          v-else-if="['permissionName', 'permissionCode', 'sort'].includes(column.dataIndex)"
        >
          <div>
            {{ text }}
          </div>
        </template>
      </template>
    </Table>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, unref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Table } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    bindRolePermissionRelation,
    queryPermissionCheckedListOfRoleId,
  } from '/@/api/system/system';
  import { RolePermissionReq } from '/@/api/system/modal/rolePermissionModel';
  import { PermissionReq, PermissionResp } from '/@/api/system/modal/permissionModel';
  import { permissionColumns } from '/@/views/system/role/role.data';

  export default defineComponent({
    name: 'RoleMenuApiModal',
    components: {
      Table,
      BasicModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const id = ref('');
      const loading = ref(false);

      const permissionList = ref<PermissionResp[]>([]);
      const permissionSelectedRowKeys = ref<string[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;
      });

      const getTitle = computed(() => '权限列表');

      const onSelectChange = (selectedRowKeys: string[]) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        permissionSelectedRowKeys.value = selectedRowKeys;
      };

      watch(
        () => id,
        () => {
          permissionList.value = [];
          permissionSelectedRowKeys.value = [];
          loadData();
        },
        { deep: true },
      );

      async function loadData() {
        const permissionReq: PermissionReq = {
          roleId: unref(id),
        };
        permissionList.value = await queryPermissionCheckedListOfRoleId(permissionReq);
        permissionSelectedRowKeys.value = [];
        if (permissionList.value && permissionList.value.length > 0) {
          for (const permissionResp of permissionList.value) {
            if (permissionResp.checked && permissionResp.id) {
              permissionSelectedRowKeys.value.push(permissionResp.id);
            }
          }
        }
      }

      async function handleSubmit() {
        try {
          const rolePermissionReq: RolePermissionReq = {
            roleId: unref(id),
            permissionIds: unref(permissionSelectedRowKeys),
          };
          await bindRolePermissionRelation(rolePermissionReq);
          closeModal();
          createMessage.success('保存成功');
          emit('success', {
            isUpdate: unref(isUpdate),
            values: { id: unref(id) },
          });
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          if (msg) {
            createMessage.error(msg);
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      onMounted(() => {
        loadData();
      });

      return {
        permissionColumns,
        roleId: id,
        registerModal,
        getTitle,
        loading,
        handleSubmit,
        permissionList,
        permissionSelectedRowKeys,
        onSelectChange,
      };
    },
  });
</script>
<style lang="less" scoped></style>
